package com.qxp.simplerpc.connect;

import com.qxp.simplerpc.AbstractInvoker;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.*;
@SuppressWarnings("unchecked")
public class RpcClientInvoker extends AbstractInvoker {
    private static Logger logger = LoggerFactory.getLogger(RpcClientInvoker.class);

    @Autowired
    private RpcClientHandler rpcClientHandler;
    @Override
    public  <T> T invoke(InvokerMessage invokerMessage) {
        try {
            rpcClientHandler.send(invokerMessage);
            //getRpcClientHandler().send(invokerMessage);
            connect(invokerMessage,-1,true,null);
        }catch (Exception ex){
            logger.error("client do invoke error",ex);
            connect(invokerMessage,-1,false,ex);
        }
        ExecutorService es = Executors.newSingleThreadExecutor();
        // 发送消息
        Future future = es.submit(() -> rpcClientHandler.getMethodInvokerResult(invokerMessage.getToken()));
        es.shutdown(); // 线程执行完毕之后关闭线程池
        try {
            return (T)future.get(30,TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("client do invoke error",e);
        }
        throw  new RpcException("client do invoke error");
    }
    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    @Autowired
    public void setRpcClientHandler(RpcClientHandler rpcClientHandler) {
        this.rpcClientHandler = rpcClientHandler;
    }
}
